import { Component, OnDestroy, OnInit, ViewChild, inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { MatTabGroup, MatTabsModule } from '@angular/material/tabs';
import { Subscription } from 'rxjs';
import { DataService } from 'src/app/core/data.service';
import { AcsService } from '../core/acs.service';
import { FeatureFlagsService } from '../core/feature-flags.service';
import { EmailSmsDialogData } from './email-sms-dialog-data';
import { MatButtonModule } from '@angular/material/button';
import { FormsModule } from '@angular/forms';
import { NgIf } from '@angular/common';
import { MatIconModule } from '@angular/material/icon';

declare const CUSTOMER_EMAIL_ADDRESS: string;
declare const CUSTOMER_PHONE_NUMBER: string;

@Component({
    selector: 'app-email-sms-dialog',
    templateUrl: './email-sms-dialog.component.html',
    styleUrls: ['./email-sms-dialog.component.scss'],
    standalone: true,
    imports: [MatDialogModule, MatIconModule, MatTabsModule, NgIf, FormsModule, MatButtonModule]
})
export class EmailSmsDialogComponent implements OnInit, OnDestroy {
  title = '';
  prompt = '';
  selectedLanguage = 'en';
  emailSubject = '';
  emailBody = '';
  emailAddress = '';
  error = '';
  smsMessage = '';
  emailSent = false;
  smsSent = false;
  placeholder = `Example:
Order is delayed 2 days.
5% discount off order.
We're sorry.`
  subscription = new Subscription();

  dataService = inject(DataService);
  acsService = inject(AcsService);
  dialogRef = inject(MatDialogRef<EmailSmsDialogComponent>);
  featureFlags = inject(FeatureFlagsService);
  data: EmailSmsDialogData = inject(MAT_DIALOG_DATA);

  @ViewChild('tabgroup', { static: true }) tabGroup!: MatTabGroup;

  ngOnInit() {
    this.title = this.data instanceof Error ? '' : this.data.title;
      console.log("eeee");
      this.fetchPrompt();
      console.log("ddddd");
  }

    fetchPrompt() {
        this.prompt = '正在生成 prompt...';
        this.dataService.getPromptByApi2(this.data.customerName, 'xxx@qq.com', this.selectedLanguage, this.data.company).subscribe(

            (data: any) => {
                console.log(data.data);
                this.prompt = data.data; // 假设 API 返回的数据有一个 `prompt` 属性
            },
            (error) => {
                console.log('Error fetching prompt:', error);
                console.error('Error fetching prompt:', error);
            }
        );
        console.log("hahah");
    }

  getFirstName(customerName: string) {
    if (customerName && customerName.indexOf(' ') > -1) {
      return customerName.split(' ')[0];
    }
    return customerName;
  }

  async generateEmailSmsMessages() {
    this.error = '';

    this.subscription.add(
      this.dataService.completeEmailSmsMessagesByApi3(this.prompt, this.data.company, this.getFirstName(this.data.customerName), this.selectedLanguage)
        .subscribe((data) => {
          if (data.status) {
            this.emailSubject = data.emailSubject;
            this.emailBody = data.emailBody;
            this.smsMessage = data.sms;
            this.tabGroup.selectedIndex = 1;
          }
          else {
            this.error = data.error;
          }
        })
    );
  }

  sendEmail() {
    // if (this.featureFlags.acsEmailEnabled) {
    if (true) {
      // Using CUSTOMER_EMAIL_ADDRESS instead of this.data.email for testing purposes
      this.subscription.add(
        this.acsService.sendEmailByListmonk(this.emailSubject, this.emailBody,
            this.getFirstName(this.data.customerName), CUSTOMER_EMAIL_ADDRESS /* this.data.email */)
          .subscribe(res => {
            console.log('Email sent:', res);
            if (res.status) {
              this.emailSent = true;
            }
          })
      );
    }
    else {
      this.emailSent = true;
    }
  }

  sendSms() {
    if (this.featureFlags.acsPhoneEnabled) {
      // Using CUSTOMER_PHONE_NUMBER instead of this.data.customerPhoneNumber for testing purposes
      this.subscription.add(
        this.acsService.sendSms(this.smsMessage, CUSTOMER_PHONE_NUMBER /* this.data.customerPhoneNumber */).subscribe(res => {
          if (res.status) {
            this.smsSent = true;
          }
        })
      );
    }
    else {
      this.smsSent = true;
    }
  }

    // 更新后的函数，当语言选择发生变化时调用
    onLanguageChange() {
        // 可以在这里根据 selectedLanguage 做相应的处理
        console.log('Selected Language:', this.selectedLanguage);
        // 你可以调用其他函数来处理语言切换后的逻辑
        this.updateDataBasedOnLanguage(this.selectedLanguage);
    }

    // 更新数据的逻辑，可以根据语言来更新内容
    updateDataBasedOnLanguage(language: string) {
        if (language === 'zh') {
            console.log('切换到中文');
            // this.selectedLanguage = '请用中文回答我。';
            // 执行你需要的语言切换逻辑，比如加载特定语言的数据
        } else if (language === 'es') {
            console.log('切换到西班牙语');
            // this.selectedLanguage = '请用西班牙语回答我。';
            // 加载西班牙语的相关数据
        } else {
            console.log('切换到英语');
            // this.selectedLanguage = '请用英语回答我。';
            // 默认是英语的逻辑
        }
    }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

}
